package org.easy.eao.spring.hibernate;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.Set;

import org.easy.eao.annotations.hibernate.Lock;
import org.easy.eao.annotations.hibernate.LockEnum;
import org.easy.eao.utils.ActionUtils;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

public class LockAction extends HibernateActionSupport<Lock> {

	private LockMode mode;
	
	@Override
	public void initialize(Annotation annotation, Method method, Class<?> clz) {
		super.initialize(annotation, method, clz);
		LockEnum type = LockEnum.valueOf(this.annotation.value());
		this.mode = type.getMode();
	}
	
	@Override
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Object execute(final Object[] parameters) {
		return getHibernateTemplate().execute(new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Set<Object> entities = ActionUtils.getAllObjects(parameters);
				for (Object entity : entities)
					session.lock(entity, mode);
				if (parameters.length == 1)
					return parameters[0];
				else
					return parameters;
			}
		});
	}

}
